package com.h3c.web.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.h3c.dal.common.TableConstant;
import com.h3c.dal.dao.CasssoResourceDAO;
import com.h3c.dal.dao.CasssoRoleResourceRelationDAO;
import com.h3c.dal.entity.CasssoResourceDO;
import com.h3c.dal.entity.CasssoRoleResourceRelationDO;
import com.h3c.dal.entity.query.CasssoResourceQuery;
import com.h3c.dal.entity.query.CasssoRoleResourceRelationQuery;
import com.h3c.web.common.constant.SessionConstant;
import com.h3c.web.common.constant.UrlConstant;

/**
 * 
 * @ClassName: RoleAuthInterceptor 
 * @Description: 角色授权
 * @author: d14287
 * @date: 2017年5月20日 下午4:55:06
 */
public class RoleAuthInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private CasssoRoleResourceRelationDAO casssoRoleResourceRelationDAO;
	@Autowired
	private CasssoResourceDAO casssoResourceDAO;

	@SuppressWarnings("unchecked")
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String requestURL = request.getRequestURL().toString();

		CasssoResourceQuery resQuery = new CasssoResourceQuery();
		resQuery.createCriteria().andResUrlEqualTo(requestURL).andStatusEqualTo(TableConstant.COMMON_STATUS_NORMAL);
		List<CasssoResourceDO> resList = casssoResourceDAO.selectByExample(resQuery);
		if (resList == null || resList.isEmpty()) {
			response.sendRedirect(UrlConstant.CAS_NO_AUTH);
			return false;
		}

		String roleId = (String) request.getSession().getAttribute(SessionConstant.ROLE_ID);
		for (CasssoResourceDO res : resList) {
			CasssoRoleResourceRelationQuery roleResExample = new CasssoRoleResourceRelationQuery();
			roleResExample.createCriteria().andResIdEqualTo(res.getResId()).andRoleIdEqualTo(roleId)
					.andStatusEqualTo(TableConstant.COMMON_STATUS_NORMAL);
			List<CasssoRoleResourceRelationDO> roleResList = casssoRoleResourceRelationDAO
					.selectByExample(roleResExample);
			if (roleResList != null && !roleResList.isEmpty())
				return true;
		}
		response.sendRedirect(UrlConstant.CAS_NO_AUTH);
		return false;
	}
}
